var fs = require('fs');
var util = require('util');
var unzip = require('unzip');
var JSZip = require('jszip');
var zip = new JSZip();

exports.unzip = function(sourceZip, targetDir, callback) {
	try {
		var readStream = fs.createReadStream(sourceZip);
		var writeStream = unzip.Extract({
			path: targetDir
		});
		// readStream.pipe(writeStream);
		// .on('finish', function() {
		// 	process.nextTick(function() {
		// 		console.log("结束解压，准备回调");
		// 		callback(null, null);
		// 	});

		// });
		// writeStream.end(function(){
		//         console.log("结束解压，准备回调");
		// 		callback(null, null);

		// });
		// 方法一直接使用readStream.pipe(writeStream);缺点是无法确定什么时候执行完
		//方法二
		readStream.on('data', function(chunk) { // 当有数据流出时，写入数据
			if (writeStream.write(chunk) === false) { // 如果没有写完，暂停读取流
				readStream.pause();
			}
		});
		writeStream.on('drain', function() { // 写完后，继续读取
			readStream.resume();
		});
		readStream.on('end', function() { // 当没有数据时，关闭数据流
			writeStream.end(function() {
				console.error("解压" + sourceZip + "完成");
				callback();
			});
		});
		writeStream.on('finish', function() {

		});
	} catch (err) {
		console.log(err);
		callback(err);
	}

}

// exports.zip = function(sourcePath, targetPath, callback) {
// 	console.log("开始压缩...");
// 	console.log(sourcePath);
// 	console.log(targetPath);
// 	var beginTime = new Date(); //开始时间
// 	var walk = function(dirPath, dirName) {
// 		fs.readdir(dirPath, function(err, files) {
// 			if (files.length == 0) {
// 				zip.folder(dirName);
// 				return;
// 			}
// 			files.forEach(function(item) {
// 				var tmpPath = path.join(dirPath, item);
// 				fs.stat(tmpPath, function(err, data)) {
// 					if (data.isDirectory()) {
// 						if (dirName == null || dirName == "") {
// 							walk(tmpPath, item);
// 						} else {
// 							walk(tmpPath, dirName + '/' + item);
// 						}
// 					} else {
// 						zip.folder(dirName).file(item, fs.readFileSync(tmpPath));
// 					}
// 				}
// 			});

// 		});
// 	};
// 	walk(sourcePath, "");
// 	var data = zip.generate({
// 		base64: false,
// 		compression: 'DEFLATE'
// 	});
// 	fs.writeFile(targetPath, data, 'binary', function() {
// 		console.log('结束压缩...');
// 		var endTime = new Date(); //结束时间
// 		var timeConsuming = endTime.getTime() - beginTime.getTime();
// 		console.log("压缩" + sourcePath + "耗费时间:" + timeConsuming + "ms");
// 	});
// }

exports.zip = function(sourcePath, targetPath, callback) {
	console.log("开始压缩...");
	var beginTime = new Date(); //开始时间
	var walk = function(dirPath, dirName) {
		files = fs.readdirSync(dirPath);
		if (0 == files.length) {
			zip.folder(dirName);
			return;
		}
		files.forEach(function(item) {
			var tmpPath = dirPath + '/' + item,
				stats = fs.statSync(tmpPath);
			if (stats.isDirectory()) {
				if(dirName == null || dirName == ""){
                    walk(tmpPath, item);
				}else{
					walk(tmpPath, dirName + '/' + item);
				}

			} else {
				zip.folder(dirName).file(item, fs.readFileSync(tmpPath));
			}
		});
	};
	walk(sourcePath, "");
	var data = zip.generate({
		base64: false,
		compression: 'DEFLATE',
		type:"nodebuffer"
	});
	fs.writeFile(targetPath, data, 'binary', function(err) {
		if(err){
           callback(err,null);
		}
		console.log('结束压缩...');
		var endTime = new Date(); //结束时间
		var timeConsuming = endTime.getTime() - beginTime.getTime();
		console.log("压缩" + sourcePath + "耗费时间:" + timeConsuming + "ms");
		callback();
	});

}